package me.suntao.javaio.server.nio2;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 服务端接入客户端请求代码
 */
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Nio2EchoServerHandler> {
  @Override
  public void completed(AsynchronousSocketChannel result, Nio2EchoServerHandler attachment) {
    //接入客户端
    attachment.socketChannel.accept(attachment,this);
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    result.read(buffer, buffer,new ReadCompletionHandler(result));
  }

  @Override public void failed(Throwable exc, Nio2EchoServerHandler attachment) {
    exc.printStackTrace();
    attachment.latch.countDown();
  }
}
